package com.itheima.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.*;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    EmpService empService;

    @Autowired
    StudentService studentService;

    //分页查询
    @Override
    public Result pageQuery(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        Page<Clazz> clazzPage = Page.of(page, pageSize);
        this.lambdaQuery().like(!StrUtil.isBlank(name), Clazz::getName, name)
                .between(Objects.nonNull(begin) && Objects.nonNull(end), Clazz::getEndDate, begin, end)
                .page(clazzPage);
        List<Clazz> clazzList = clazzPage.getRecords().stream().peek(clazz -> {
            Emp emp = empService.getById(clazz.getMasterId());
            if (Objects.nonNull(emp)) {
                clazz.setMasterName(emp.getName());
            }
            LocalDate now = LocalDate.now();
            if (clazz.getBeginDate().isAfter(now)) {
                clazz.setStatus("未开班");
            } else if (clazz.getEndDate().isBefore(now)) {
                clazz.setStatus("已结课");
            } else {
                clazz.setStatus("在读");
            }
        }).toList();
        return Result.success(new PageResult<>(clazzPage.getTotal(), clazzList));
    }

    @Override
    public void deleteClazz(Integer id) {
        long count = studentService.count(new LambdaQueryWrapper<Student>().eq(Student::getClazzId, id));
        if (count >0) {
            throw new RuntimeException("该班级有学生不能删除");
        }
        this.removeById(id);
    }
}
